from flask import g
from flask import request
from flask import session, jsonify

from info import constants
from info import redis_store
from info.models import User, News, Category
from info.response_code import RET
from info.utils.commons import user_login_data
from . import index_blue
from flask import render_template, current_app


# 首页新闻获取
# 请求路径  /newslist
# 请求方式 GET
# 请求参数 cid page per_page
# 返回值 data值
@index_blue.route('/newslist')
def newslist():
    # 获取参数
    cid = request.args.get('cid', '1')
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '10')
    # 参数类型转换
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        page = 1
        per_page = 10
    # 分页查询
    try:
        # 判断分类编号是否不等于1
        filter_condition = ''
        if cid != '1':
            filter_condition = (News.category_id == cid)
        paginate = News.query.filter(filter_condition).order_by(News.create_time.desc()).paginate(page, per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='获取新闻失败')
    # 获取分页对象属性,总页数,当前页,当前页对象列表
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items
    # 将对象列表转成字典列表
    news_list = []
    for item in items:
        news_list.append(item.to_dict())
    # 拼接数据 返回响应

    return jsonify(errno=RET.OK, errmsg='获取分类信息成功', totalPage=totalPage, currentPage=currentPage, newsList=news_list)


@index_blue.route('/', methods=['GET', 'POST'])
@user_login_data
def show_index():
    # # 取出session中用户的编号
    # user_id = session.get('user_id')
    # # 根据user_id取出用户对象
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    # 取出热门新闻前十条
    try:
        news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询新闻失败')
    # 将对象列表,转成字典列表
    click_news_list = []
    for item in news:
        click_news_list.append(item.to_dict())

    # 查询所有分类信息
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='获取分类失败')
    # 将分类信息转成字典列表
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())
    # 携带用户数据,渲染页面
    data = {
        'user_info': g.user.to_dict() if g.user else "",
        'click_news_list': click_news_list,
        'categories': category_list
    }
    return render_template('news/index.html', data=data)




    # 测试redis
    # redis_store.set('name', 'haha')
    # print(redis_store.get('name'))

    # # 测试session存取
    # session['age'] = 10
    # print(session.get('age'))

    # 测试日志输出  来替代print打印
    # logging.debug('调试级别信息')
    # logging.info('详细级别信息')
    # logging.warning('警告级别信息')
    # logging.error('错误信息')

    # 使用current_app来使用  控制台内有分割线分割 日志内记录完全一样
    # current_app.logger.debug('调试级别信息')
    # current_app.logger.info('详细级别信息')
    # current_app.logger.warning('警告级别信息')
    # current_app.logger.error('错误信息')


# 处理logo
@index_blue.route('/favicon.ico')
def logo():
    return current_app.send_static_file('news/favicon.ico')
